package fr.mywiki.business.utils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * This class contains several methods useful for the management of
 * <code>Collection</code> objects.
 * 
 * @author tlombard
 */
public class CollectUtils {
	private CollectUtils() {
	}

	/**
	 * Computes and returns the collection which is the intersection of
	 * collections a and b. x belongs to the intersection of a and b if and only
	 * if x belongs to a and x belongs to b.
	 * 
	 * @param a
	 *          a <code>Collection</code> object.
	 * @param b
	 *          a <code>Collection</code> object.
	 * @return a <code>Collection</code> object.
	 */
	public static Collection intersection(Collection a, Collection b) {
		Collection result = new ArrayList();
		Iterator it = a.iterator();
		while (it.hasNext()) {
			Object obj = it.next();
			if (b.contains(obj))
				result.add(obj);
		}
		return result;
	}

	/**
	 * Computes and returns the collection which is the union of collections a and
	 * b. x belongs to the union of a and b if and only if x belongs to a or (not
	 * exclusive) x belongs to b.
	 * 
	 * @param a
	 *          a <code>Collection</code> object.
	 * @param b
	 *          a <code>Collection</code> object.
	 * @return a <code>Collection</code> object.
	 */
	public static Collection union(Collection a, Collection b) {
		Collection result = new ArrayList(a);
		Iterator it = b.iterator();
		while (it.hasNext()) {
			Object obj = it.next();
			if (!result.contains(obj))
				result.add(obj);
		}
		return result;
	}

	/**
	 * Returns the first occurrence of <code>elem</code> in <code>list</code>
	 * from <code>from</code>-th position.
	 * 
	 * @param list
	 *          a List object
	 * @param elem
	 *          any object
	 * @param from
	 *          an integer
	 * @return -1 if the element could not be found in list, its absolute position
	 *         otherwise
	 * @see ArrayList#indexOf(java.lang.Object)
	 */
	public static int indexOf(List list, Object elem, int from) {
		List sub = list.subList(from, list.size());

		int index = sub.indexOf(elem);
		return index == -1 ? -1 : from + index;
	}

	/**
	 * Returns a list containing the same elements but in the opposite order.
	 * 
	 * @param list
	 *          any <code>List</code> object.
	 * @return a <code>List</code> object.
	 */
	public static List invert(List list) {
		List list2 = new ArrayList();
		for (int i = list.size() - 1; i >= 0; i--)
			list2.add(list.get(i));
		return list2;
	}
}
